package com.leetcode.algorithms.one.problem8;

import org.junit.Test;

public class String2Integer {
    @Test
    public void run(){
        char c ='0';
        char c2 = '-';

        System.out.println((byte )c);
        System.out.println((byte )c2);
    }

    @Test
    public void run1(){
        String s = "-000000000000001";

        System.out.println(myAtoi(s));
    }


    public int myAtoi(String str) {
        if(str==null||str.trim().equals(""))
            return 0;
        str=str.trim();
        boolean isFS=false;
        if(str.charAt(0)=='-')
            isFS=true;


        StringBuilder sb = new StringBuilder("0");
        int len = str.length();
        boolean hasBegin = false;

        for(int i=0;i<len;i++){
            if(!hasBegin){
                char c = str.charAt(i);
                if(c=='-'||c=='+'){
                    if(i>0)
                        return 0;
                }else if(c=='0')
                    sb.setCharAt(0,c);
                else if (c > '0' && c <= '9') {
                    sb.setCharAt(0,c);
                    hasBegin=true;
                }
                else
                    return 0;

            }else{
                char c = str.charAt(i);
                if(c>='0'&&c<='9'&&sb.length()<11)
                    sb.append(c);
                else
                    break;
            }
        }
//        if(sb.length()==1)
//            return 0;

        long l =Long.parseLong(sb.toString());
        if(isFS)
            l=0-l;
        if(l>Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        if(l<Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        return (int) l;


    }


}
